package com.zr.bookcorner.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.model.BookModel;
import com.zh.baselibrary.model.TaskModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.model.CurrentTime;
import com.zh.model.home.TokenBean;
import com.zr.bookcorner.activity.LimitActivity;
import com.zr.bookcorner.broadcast.ServiceRestartReceiver;
import com.zr.bookcorner.utils.DeviceUtil;
import com.zr.websocket.ReconnectManager;
import com.zr.websocket.WebSocketSend;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @author EnzoChan
 * @create 2019/3/13
 * @desc:
 */
public class HeartService extends Service {
    private int INTIME =  6 * 1000;
    private int PERIOD_TIME = 5 * 60 * 1000;

    private Timer mTimer;

    private String uuid;
    BookModel model;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        uuid = PhoneUtil.getUUID(this);
        mTimer = new Timer();
        PeriodTask periodTask = new PeriodTask();
        mTimer.schedule(periodTask, INTIME, PERIOD_TIME);
        model = new BookModel(getBaseContext());
        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    public class PeriodTask extends TimerTask {
        public void run() {
            if(!TextUtils.isEmpty(BaseConstant.DEVICE_TOKEN))
                heartbeat();
            else
                login();
             Long deadLine = ShareManager.getLong(HeartService.this, BaseConstant.AUTHORIZATION_DEADLINE_BOOK);

            if (deadLine != 0 && Long.valueOf(deadLine) - System.currentTimeMillis() < 0 && deadLine != -1) {
                Intent mIntent = new Intent(HeartService.this, LimitActivity.class);
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.putExtra(ExtraName.KEY_DATA, 1);
                startActivity(mIntent);
            } else {
                //如果在运行就关闭界面
                Intent mIntent = new Intent();
                mIntent.putExtra(ExtraName.KEY_DATA, 1 + "");
                mIntent.setAction(BaseConstant.BROAT_CAST_ACTION_UN_LOCK);
                HeartService.this.sendBroadcast(mIntent);
            }
        }
    }


    public void heartbeat() {
           model.heartbeat(uuid)
                   .subscribeOn(Schedulers.io())//启动订阅线程
                   .observeOn(AndroidSchedulers.mainThread())//切换至主线程
                   .subscribe(new RxSubscribe<BaseResp<Object>>() {
               @Override
               public void onSuccess(BaseResp<Object> objectBaseResp) throws Exception {
                   if(ReconnectManager.reconnectManager!=null)
                       ReconnectManager.reconnectManager.isReconnect();
                   else {
                       Intent intent = new Intent();
                       intent.setAction(BaseConstant.BROAT_CAST_ACTION_RESTART_SERVICE);
                       intent.putExtra(ExtraName.KEY_DATA, ServiceRestartReceiver.START_WEB_SOCKET);
                       sendBroadcast(intent);
                   }
                   if(objectBaseResp.getCode()!=0)
                       login();
               }

               @Override
               public void onHint(String hint) {
                   BaseConstant.DEVICE_TOKEN = "";
                   login();
               }
           });
    }
    private void login(){
        model.equipmentLogin(uuid)
                .subscribeOn(Schedulers.io())//启动订阅线程
                .subscribe(new RxSubscribe<BaseResp<TokenBean>>() {
            @Override
            public void onSuccess(BaseResp<TokenBean> tokenBeanBaseResp) throws Exception {
                reportBaseInfo();
            }

            @Override
            public void onHint(String hint) {

            }
        });
    }
    private void reportBaseInfo(){
        model.reportBaseInfo(DeviceUtil.getEquipmentLogin(getBaseContext()))
                .subscribeOn(Schedulers.io())//启动订阅线程
                .subscribe(new RxSubscribe<BaseResp<CurrentTime>>() {
                    @Override
                    public void onSuccess(BaseResp<CurrentTime> currentTimeBaseResp) throws Exception { }
                    @Override
                    public void onHint(String hint) { }});
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Integer integer) {
        if(integer == 99) {
            LogUtils.e("heart : send");
            EventBus.getDefault().post(new WebSocketSend(PhoneUtil.getUUID(getApplicationContext()), "1"));
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(VoiceEvent event) {
        TTSUtils.getInstance().speak(event.getTip());
    }

    @Override
    public void onDestroy() {
        if(EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        mTimer.cancel();
        Intent intent = new Intent();
        intent.setAction(BaseConstant.BROAT_CAST_ACTION_RESTART_SERVICE);
        intent.putExtra(ExtraName.KEY_DATA, ServiceRestartReceiver.START_HEART);
        sendBroadcast(intent);
        super.onDestroy();
    }
}
